import sqlite3, datetime, json
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *

def verify_email(request, token):
	initialize(request)
	output = get_links(request)
	
	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()

	if token != None:
		sql_cursor.execute("""update staff set email_token = null, email_verified = 1 where email_token = ?""", (token,))
		sql_cursor.execute("""update students set email_token = null, email_verified = 1 where email_token = ?""", (token,))
		sql_cursor.execute("""update parents set email_token = null, email_verified = 1 where email_token = ?""", (token,))
		sql_connection.commit()
		output += 'You email address has been verified.'
	
	elif 'verification_email' in request.POST.keys():
		
		token = random_hex()[:8]

		sql_cursor.execute("""update staff set email_token = ? where email = ?""", (token, request.POST["verification_email"]))
		sql_cursor.execute("""update students set email_token = ? where email = ?""", (token, request.POST["verification_email"]))
		sql_cursor.execute("""update parents set email_token = ? where email = ?""", (token, request.POST["verification_email"]))
		sql_connection.commit()
		
		if not send_email(request.POST["verification_email"], global_vars["mail_messages"]["verify_email"][0], global_vars["mail_messages"]["verify_email"][1] % (token)):
			output += '<p class="error_message">Error sending email to user!</p>'
		else:
			output += 'Verification email sent.'
	
	else:
		output += (
		'<h2>Verify email</h2><br />'
		'<form action="?" method="post">'
		'Your email address: <input type="text" name="verification_email"><br />'
		'<input type="submit" value="Send verification email">'
		'</form>'
		)
	return HttpResponse(header+output+footer)
	

def reset_password(request, token):	
	initialize(request)
	output = get_links(request)
	
	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()    

	if token != None:
		password_updated = False
		if 'password_1' in request.POST.keys():
			if request.POST["password_1"] == request.POST["password_2"]:
				salt = random_hex()
				pass_hash = pass_derivation(request.POST["password_1"], salt)

				sql_cursor.execute("""update staff set pass_hash = ?, pass_salt = ?, email_token = null where email_token = ?""", (pass_hash, salt, token))
				sql_cursor.execute("""update students set pass_hash = ?, pass_salt = ?, email_token = null where email_token = ?""", (pass_hash, salt, token))
				sql_cursor.execute("""update parents set pass_hash = ?, pass_salt = ?, email_token = null where email_token = ?""", (pass_hash, salt, token))
				sql_connection.commit()
				output += 'You password has been updated.'
				password_updated = True
			else:
				output += "Passwords didn't match."
		
		if not password_updated:
			output += (
			'<h2>Reset password</h2><br />'
			'<form action="?" method="post">'
			'New password: <input type="password" name="password_1"><br />'
			'Retype new password: <input type="password" name="password_2"><br />'
			'<input type="submit" value="Reset password">'
			'</form>'
			)
	elif 'reset_email' in request.POST.keys():
		token = random_hex()[:8]

		sql_cursor.execute("""update staff set email_token = ? where email = ?""", (token, request.POST["reset_email"]))
		sql_cursor.execute("""update students set email_token = ? where email = ?""", (token, request.POST["reset_email"]))
		sql_cursor.execute("""update parents set email_token = ? where email = ?""", (token, request.POST["reset_email"]))
		sql_connection.commit()
		
		if not send_email(request.POST["reset_email"], global_vars["mail_messages"]["reset_email"][0], global_vars["mail_messages"]["reset_email"][1] % (token)):
			output += '<p class="error_message">Error sending email to user!</p>'
		else:
			output += 'Please check yor email to reset your password.'
		
	else:
		output += (
		'<h2>Reset password</h2><br />'
		'This will send you an email about how to reset your password.<br />'
		'<form action="?" method="post">'
		'Enter your email address: <input type="text" name="reset_email"><br />'
		'<input type="submit" value="Reset password">'
		'</form>'
		)
	
	return HttpResponse(header+output+footer)
	
	
def index(request, special_request):
	initialize(request)
	
	output = ""
	
	if special_request == 'log-out/':
		log_out(request)
		
	error = ""
	if 'email' in request.POST.keys():
		log_in_result = log_in(request, request.POST["email"], request.POST["password"], 0)
		if log_in_result == 1:
			print "not staff"
			log_in_result = log_in(request, request.POST["email"], request.POST["password"], 1)
			if log_in_result == 1:
				print "not student"
				log_in_result = log_in(request, request.POST["email"], request.POST["password"], 2)
				if log_in_result == 1:
					error = '<p class="error_message">Wrong email and password combination.</p>'
		if log_in_result == 2:
			error = '<p class="error_message">Please <a href="/users/verify-email/">verify your email</a> in order to log in.</p>'
	
	# Get links after log in!
	output += get_links(request)
	output += error
	
	if not request.session["user"]["logged_in"]:
		output += """
		<div class="col-xs-12">
        <div class="login-box"><h2>Log In</h2>
        <form action="/users/" method="post">
        <table class="">
		<input class="login" type="text" name="email" placeholder="example@email.com"/>
		<input class="login" type="password" name="password" placeholder="password"/>
		<input class="btn btn-primary" type="submit" value="Log in"/>
		</table>
		</form>
        </div>
        </div>
		"""
	
	return HttpResponse(header + output + footer)
